<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 选择商品分类区域 -->
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row class="cate-opt">
        <!-- 级联选择框 -->
        <span>
          选择商品分类:
          <el-cascader
            v-model="selectedCateKeys"
            :options="categoriesData"
            :props="categoriesDataProps"
            clearable
            @change="handleChange"
          ></el-cascader>
        </span>
      </el-row>
      <!-- tab区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加参数</el-button>
          <el-table :data="manyData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <!-- tag区域 -->
              <template slot-scope="scoped">
                <el-tag
                  closable
                  v-for="(item,i) in scoped.row.attr_vals"
                  :key="i"
                  @close="handleClosed(i,scoped.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button
                  size="mini"
                  type="primary"
                  @click="changeData(scoped.row.attr_id,scoped.row.cat_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="dataDelete(scoped.row.attr_id,scoped.row.cat_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
          >添加属性</el-button>
          <!-- 静态属性 -->
          <el-table :data="onlyData" style="width: 100%" border stripe>
            <el-table-column type="expand">
              <!-- tag区域 -->
              <template slot-scope="scoped">
                <el-tag
                  closable
                  v-for="(item,i) in scoped.row.attr_vals"
                  :key="i"
                  @close="handleClosed(i,scoped.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scoped.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button
                  size="mini"
                  type="primary"
                  @click="changeData(scoped.row.attr_id,scoped.row.cat_id)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="dataDelete(scoped.row.attr_id,scoped.row.cat_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加静态属性和动态参数对话框 -->

      <el-dialog
        :title="dialogText"
        :visible.sync="addDialogVisible"
        width="50%"
        @closed="dialogClosed"
      >
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="活动名称" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改参数对话框 -->
      <el-dialog
        :title="editDialogText"
        :visible.sync="editDialogVisible"
        width="50%"
        @closed="dialogClosed"
      >
        <el-form ref="addFormRef" :model="editForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="活动名称" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="changeConfirmSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      categoriesData: [],
      //   商品列表数据源
      categoriesDataProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
        // checkStrictly: 'true'
      },
      //   级联选择框双向绑定数组
      selectedCateKeys: [],
      activeName: 'many',
      manyData: [],
      onlyData: [],
      addDialogVisible: false,
      //   添加属性form表单绑定数据
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: '',
        attr_id: '',
        attr_name: '',
        cat_id: ''
      },

      //   验证规则
      addFormRules: {
        attr_name: {
          required: true,
          message: '请输入活动名称',
          trigger: 'blur'
        }
      },
      editDialogVisible: false
    }
  },
  created() {
    this.getCategoriesList()
  },
  methods: {
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories')
      //   console.log(res)
      if (res.meta.status !== 200) return this.$msg('获取商品列表失败')
      this.categoriesData = res.data
    },
    // 级联选择框变化触发的函数
    async handleChange() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyData = []
        this.onlyData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )

      if (res.meta.status !== 200) return this.$msg('获取参数失败')

      res.data.forEach(item => {
        // console.log(item.attr_vals)
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res)
      if (this.activeName !== 'many') this.onlyData = res.data
      this.manyData = res.data
      //   console.log(res.data)
    },
    // 页签点击处理函数
    handleTabClick() {
      this.handleChange()
      //   console.log(this.activeName)
    },
    dialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮  提交参数
    confirmSubmit() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$msg('不可为空')
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        console.log(res)
        if (res.meta.status !== 201) return this.$msg('添加属性失败')
        this.$msg('添加属性成功', 'success')
        this.handleChange()
        this.addDialogVisible = false
      })
    },
    // 根据id获取参数
    async changeData(attr_id, cat_id) {
      //   console.log(id)
      const { data: res } = await this.$http.get(
        `categories/${cat_id}/attributes/${attr_id}`,
        {
          attr_sel: this.activeName
        }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$msg('获取参数失败')
      this.editForm = res.data

      this.editDialogVisible = true
    },
    changeConfirmSubmit() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$msg('不可为空')
        const { data: res } = await this.$http.put(
          `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) return this.$msg('提交参数失败')
        this.handleChange((this.editDialogVisible = false))
      })
    },
    async dataDelete(attr_id, cat_id) {
      const confirmDelete = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmDelete !== 'confirm') return this.$msg('已取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${cat_id}/attributes/${attr_id}`
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$msg('删除失败')
      this.handleChange()
    },
    // enter和失去焦点都可以触发
    async handleInputConfirm(row) {
      //   console.log('ok')
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      this.putData(row)
    },
    async putData(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$msg('提交信息失败')
      this.$msg('提交信息成功', 'success')
    },
    showInput(row) {
      row.inputVisible = true
      //   让文本框自动获得焦点
      // nextTick方法的作用 就是当页面上元素被重新渲染之后,才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClosed(i, row) {
      row.attr_vals.splice(i, 1)
      console.log(this)
      this.putData(row)
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) return true
      return false
    },
    cateId() {
      if (this.selectedCateKeys.length === 3) return this.selectedCateKeys[2]
      return null
    },
    dialogText() {
      if (this.activeName === 'many') return '添加动态参数'
      return '添加静态属性'
    },
    editDialogText() {
      if (this.activeName === 'many') return '修改动态参数'
      return '修改静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cate-opt {
  margin: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>